<template>
	<jk-dialog
		v-model="showDialog"
		:confirm-btn-loading="saveBtnLoading"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		:show-confirm-btn="pageType !== 'detail'"
		:show-content-loading="showLoading"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-峰谷用电`"
		width="1100px"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form
			ref="ruleForm"
			:hide-required-asterisk="pageType === 'detail'"
			:model="ruleForm"
			:rules="rules"
			:show-message="false"
			label-width="110px"
		>
			<el-form-item class="margin-bottom-10" label="配置项" prop="configName">
				<el-input
					v-model="ruleForm.configName"
					:disabled="pageType === 'detail'"
					placeholder="配置项"
					size="small"
					style="width: 220px"
				/>
			</el-form-item>
			<jk-table :data="ruleForm.electricityPriceList" :height="dialogTableHeight - 140" border>
				<vxe-column v-if="pageType !== 'detail'" :width="100" align="center" field="operation" title="操作">
					<template slot="header">
						<div class="flex-center link-style " @click="onAddBtn">
							<span class="el-icon-plus"></span>
							<span>添加</span>
						</div>
					</template>
					<template slot-scope="scope">
						<el-button icon="el-icon-minus" plain size="mini" @click="onDeleteBtn(scope)"></el-button>
					</template>
				</vxe-column>
				<vxe-column :width="180" align="left" field="typeCode" title="类型">
					<template slot-scope="scope">
						<jk-select
							v-model="scope.row.typeCode"
							:disabled="pageType === 'detail'"
							:option-list="elelctorList"
							placeholder="类型"
							value-key-name="code"
						></jk-select>
					</template>
				</vxe-column>
				<vxe-column :min-width="250" align="left" field="time" title="时间">
					<template slot-scope="scope">
						<div>
							<el-time-picker
								v-model="scope.row.startTime"
								:disabled="pageType === 'detail'"
								:picker-options="{
									format: 'HH:mm:ss', // 内部处理的格式
									selectableRange: getPickerOptions(scope.row)
								}"
								format="HH:mm"
								placeholder="起始时间"
								size="small"
								style="margin-right: 5px;"
								value-format="HH:mm"
							/>
							-
							<el-time-picker
								v-model="scope.row.endTime"
								:disabled="pageType === 'detail'"
								:picker-options="{
									format: 'HH:mm:ss', // 内部处理的格式
									selectableRange: getPickerOptions(scope.row)
								}"
								format="HH:mm"
								placeholder="结束时间"
								size="small"
								value-format="HH:mm"
							/>
						</div>
					</template>
				</vxe-column>
				<vxe-column :width="180" align="right" field="price" title="单价">
					<template slot-scope="scope">
						<jk-number-input
							v-model="scope.row.price"
							:disabled="pageType === 'detail'"
							placeholder="单价"
							size="small"
						/>
					</template>
				</vxe-column>
			</jk-table>

		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '@/mixins/cal-dialog-height';
    import { createElector, updateElector, getDetailElector } from '@/api/energy/elector';
    import remoteSearchProductInput from '../../technology/order/components/remote-search-product-input/index';
    import { systemBusinessDictPage } from '@/api/basicData/businessDict';
    import Logo from '@/layout/components/Sidebar/Logo.vue';

    export default {
        mixins: [calHeight],
        components: { remoteSearchProductInput },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }

        },
        data() {
            return {
                elelctorList: [],
                tableLoading: false,
                saveBtnLoading: false,
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                yarnNameList: [],
                ruleForm: {
                    electricityPriceList: [{ ...this.defaultRowData }],
                    configName: ''
                },
                rules: {
                    configName: [{ required: true, trigger: 'blur' }]
                },
                defaultRowData: {
                    typeCode: '',
                    typeName: '',
                    price: 0,
                    startTime: '',
                    endTime: ''
                }
            };
        },
        methods: {

            onDeleteBtn(scope) {
                this.ruleForm.electricityPriceList.splice(scope.rowIndex, 1);
            },
            onAddBtn() {
                this.ruleForm.electricityPriceList.push({ ...this.defaultRowData });
            },
            convertParams(params) {
                const data = params.electricityPriceList.map(item => {
                    // 解析时间并增加 1 小时
                    const [startHour, startMinute] = item.startTime.split(':').map(Number);
                    const [endHour, endMinute] = item.endTime.split(':').map(Number);
                    // const newStartHour = (startHour + 1) % 24; // 增加1小时，24小时制 ???? 为什么会有增加一小时
                    // const newEndHour = (endHour + 1) % 24; // 增加1小时，24小时制 ???? 为什么会有增加一小时

                    // 格式化时间
                    const formatTime = (hour, minute) => `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
                    return {
                        typeCode: this.elelctorList.filter(i => i.code === item.typeCode)[0].code, // 固定值
                        typeName: this.elelctorList.filter(i => i.code === item.typeCode)[0].name, // 固定值
                        startTime: formatTime(startHour, startMinute),
                        endTime: formatTime(endHour, endMinute),
                        price: parseFloat(item.price).toFixed(5) // 保留1位小数
                    };
                });
                return {
                    configName: params.configName,
                    id: this.dataId,
                    electricityPriceList: data
                };
            },
            onConfirmBtn() {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        // 手动验证所有数据项
                        const isValid = this.ruleForm.electricityPriceList.every(item =>
                            item.typeCode &&
                            item.startTime &&
                            item.endTime &&
                            item.price > 0
                        );

                        if (!isValid) {
                            this.$tipsBar(this, 'validator'); // 提示验证失败
                            return; // 阻止后续操作
                        }
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            // 新增或修改
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const convertedParams = this.convertParams(JSON.parse(JSON.stringify(this.ruleForm)));
                const api = this.dataId ? updateElector : createElector;

                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        api(convertedParams).then(res => {
                            this.saveBtnLoading = false;
                            if (res.data.status === 200) {
                                this.$tipsBar(this, 'save');
                                this.$emit('on-finish', res.data.res);
                            }
                        });
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            // 详情
            getDetailRequest() {
                return getDetailElector({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },

            // 获取峰谷的dic
            getElectorListRequest() {
                return systemBusinessDictPage({
                    categoryCode: 'FENGGU_ELECTRIC'
                }).then(res => {
                    if (res.data.status === 200) {
                        this.elelctorList = res.data.res || [];
                    }
                });
            },

            async getDependentData() {
                this.showLoading = true;
                await this.getElectorListRequest();

                if (this.dataId) {
                    await this.getDetailRequest();
                } else {
                    // 如果没有dataId，表示是新增情况，确保有一行数据
                    if (this.ruleForm.electricityPriceList.length === 0) {
                        this.ruleForm.electricityPriceList.push({ ...this.defaultRowData });
                    }
                }

                this.showLoading = false;
            },
            // 时间禁用处理
            getPickerOptions(row) {
                // 过滤掉当前正在编辑的行
                const selectedTimes = this.ruleForm.electricityPriceList
                    .filter(item => item !== row && item.startTime && item.endTime)
                    .map(item => ({
                        start: item.startTime,
                        end: item.endTime
                    }));
                // 创建禁用时间段的数组;
                const disabledRanges = selectedTimes.map(time => {
                    const [startHour, startMinute] = time.start.split(':');
                    const [endHour, endMinute] = time.end.split(':');
                    return `${startHour}:${startMinute}:00 - ${endHour}:${endMinute}:00`;
                });

                // 用于存储时间选择器的可选时间段
                const selectableRanges = [];
                const fullRange = '00:00:00 - 23:59:59';
                // console.log(disabledRanges, 'disabledRanges');
                if (disabledRanges.length === 0) {
                    // 如果没有禁用的时间段，则返回全时间范围
                    selectableRanges.push(fullRange);
                } else {
                    // 计算可选时间段
                    let lastEnd = '00:00:00';
                    disabledRanges.forEach(range => {
                        const [start, end] = range.split(' - ');
                        if (lastEnd < start) {
                            selectableRanges.push(`${lastEnd} - ${start}`);
                        }
                        lastEnd = end;
                    });

                    if (lastEnd < '23:59:59') {
                        selectableRanges.push(`${lastEnd} - 23:59:59`);
                    }
                }
                // 返回以HH:mm:ss格式的selectableRange
                return selectableRanges.length > 0 ? selectableRanges : [fullRange];
            }
        },
        watch: {
            dialogState: {
                handler(value) {
                    this.showDialog = value;
                    if (value) {
                        this.getDependentData();
                    }
                },
                immediate: true
            }
        }
    };
</script>
